import type { ProFormInstance } from '@ant-design/pro-components';
import {
  EditableProTable,
  ModalForm,
  ProForm,
  ProFormDependency,
  ProFormField,
  ProFormSelect,
  ProFormSwitch,
  ProFormText,
} from '@ant-design/pro-components';
import { Col, Row } from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import fieldconfig from './fieldconfig';
const UpdateField: React.FC<{
  onCancel: () => void;
  onSubmit: (values: any) => void;
  updateFiedShow: number;
  values: any;
}> = (props) => {
  const columns = [
    {
      title: '值(value)',
      dataIndex: 'value',
      width: '40%',
      formItemProps: {
        rules: [
          {
            required: true,
            whitespace: true,
            message: '此项是必填项',
          },
          {
            message: '必须是数字',
            pattern: /\d/,
          },
        ],
      },
    },
    {
      title: '名(label)',
      dataIndex: 'label',
      width: '40%',
      formItemProps: {
        rules: [
          {
            required: true,
            whitespace: true,
            message: '此项是必填项',
          },
        ],
      },
    },
    {
      title: '操作',
      valueType: 'option',
    },
  ];

  const formRef = useRef<ProFormInstance>();
  const [extrashow, setExtrashow] = useState(false);
  const [defaultData, setDefaultData] = useState([]);
  const [editableKeys, setEditableRowKeys] = useState<React.Key[]>(() =>
    defaultData.map((item: any) => item.id),
  );
  const ftyp = (type: string) => {
    const f = fieldconfig.fieldOptions.find((item) => item.value === type);
    return f?.type;
  };
  useEffect(() => {
    if (props?.values?.extra) {
      setDefaultData(JSON.parse(props?.values?.extra));
      setEditableRowKeys(() =>
        JSON.parse(props?.values?.extra).map((item: { id: any }) => item.id),
      );
    }
  }, [props]);
  return (
    <ModalForm
      formRef={formRef}
      title={props.updateFiedShow === 1 ? '新建字段' : '编辑字段'}
      visible={props.updateFiedShow != 0}
      onFinish={async (value) => {
        // message.success('提交成功');
        props.onSubmit(value);
        return true;
      }}
      modalProps={{
        onCancel: () => {
          props.onCancel();
          setExtrashow(false);
        },
        maskClosable: false,
        destroyOnClose: true,
      }}
      grid={true}
      rowProps={{
        gutter: [16, 0],
      }}
      onValuesChange={(changeValues) => {
        if (changeValues?.type) {
          formRef?.current?.setFieldValue('field', ftyp(changeValues?.type));
        }
      }}
    >
      <ProFormText
        colProps={{
          span: 12,
        }}
        name="name"
        label="字段名"
        tooltip="英文字母,长度不超过30"
        placeholder="请输字段名"
        initialValue={props?.values?.name}
        rules={[{ required: true }]}
      />
      <ProFormText
        colProps={{
          span: 12,
        }}
        name="title"
        label="字段标题"
        tooltip="用于表单显示"
        placeholder="请输入字段标题"
        initialValue={props?.values?.title}
        rules={[{ required: true }]}
      />
      <ProFormSelect
        colProps={{
          span: 8,
        }}
        name="type"
        label="字段类型"
        request={async () => fieldconfig.fieldOptions}
        tooltip="用于表单中的展示方式"
        placeholder="选择字段类型"
        rules={[{ required: true }]}
        initialValue={props?.values?.type}
      />
      <ProFormDependency name={['type']}>
        {({ type }) => {
          setExtrashow(fieldconfig.extraFields.includes(type));
          return (
            <ProFormText
              colProps={{
                span: 8,
              }}
              name="field"
              label="字段定义"
              tooltip="字段属性的sql表示"
              placeholder="请输入字段定义"
              initialValue={ftyp(type)}
              readonly
              rules={[{ required: true }]}
            />
          );
        }}
      </ProFormDependency>

      <ProFormText
        colProps={{
          span: 8,
        }}
        name="value"
        label="字段默认值"
        tooltip="没有可以不填"
        initialValue={props?.values?.value}
        placeholder="没有可以不填"
      />
      {extrashow && (
        <Row gutter={[16, 16]}>
          <Col span={14}>
            <ProForm.Item
              label="数据化配置选项内容"
              name="extra"
              initialValue={defaultData}
              trigger="onValuesChange"
            >
              <EditableProTable
                rowKey="id"
                toolBarRender={false}
                columns={columns}
                recordCreatorProps={{
                  newRecordType: 'dataSource',
                  position: 'bottom',
                  record: () => ({
                    id: Date.now(),
                  }),
                }}
                editable={{
                  type: 'multiple',
                  editableKeys,
                  onChange: setEditableRowKeys,
                  actionRender: (row, _, dom) => {
                    return [dom.delete];
                  },
                }}
              />
            </ProForm.Item>
          </Col>
          <Col span={10}>
            <ProFormDependency name={['extra']}>
              {({ extra }) => {
                const nextra = extra.map((item: any) => {
                  return { value: item.value, label: item.label };
                });
                return (
                  <ProFormField
                    ignoreFormItem
                    fieldProps={{
                      style: {
                        width: '100%',
                      },
                    }}
                    mode="read"
                    valueType="jsonCode"
                    text={JSON.stringify(nextra)}
                  />
                );
              }}
            </ProFormDependency>
          </Col>
        </Row>
      )}
      <ProFormSwitch
        colProps={{
          span: 8,
        }}
        initialValue={props?.values?.is_must || false}
        label="是否必填"
        name="is_must"
        tooltip="用于表单自动验证"
      />
      <ProFormSwitch
        colProps={{
          span: 8,
        }}
        initialValue={props?.values?.indexes || false}
        label="是否索引"
        name="indexes"
        tooltip="启用索引回自动在数据库表中创建索引"
      />
      <ProFormSelect
        colProps={{
          span: 8,
        }}
        name="is_show"
        label="表单显示"
        valueEnum={{
          0: '不显示',
          1: '始终显示',
          2: '新增时显示',
          3: '编辑时显示',
        }}
        initialValue={props?.values?.is_show != undefined ? props?.values?.is_show.toString() : ''}
        tooltip="用于表单中的展示方式"
        placeholder="表单显示"
        rules={[{ required: true }]}
      />
      <ProFormText
        name="remark"
        label="字段备注"
        tooltip="用于表单中的提示"
        placeholder="请输入名称"
        initialValue={props?.values?.remark}
      />
    </ModalForm>
  );
};
export default UpdateField;
